package com.stox.charting.ui.swing.event.listener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.stox.charting.ui.swing.event.ChartModelChangedEvent;
import com.stox.charting.ui.swing.model.BarSpan;
import com.stox.charting.ui.swing.model.ChartModel.ChartModelListener;
import com.stox.charting.ui.swing.model.price.PriceChartModel;
import com.stox.core.model.IBar;

public class BarSpanChangedEventListener implements ChartModelListener {

	@Override
	@SuppressWarnings("unchecked")
	public void chartModelChanged(ChartModelChangedEvent event) {
		if(event.getProperty().equalsIgnoreCase("barSpan")){
			PriceChartModel<IBar> chartModel = (PriceChartModel<IBar>)event.getSource();
			
			List<IBar> data = chartModel.getMinimumBarSpanData();
			List<IBar> modifiedData = new ArrayList<IBar>();
			Calendar calendar = Calendar.getInstance();
			int previousUnit = -1;
			IBar iBar = null;
			
			for(int i = 0; i < data.size(); i++){
				IBar bar = data.get(i);
				calendar.setTime(bar.getDate());
				int currentUnit = calendar.get(chartModel.getBarSpan().getUnit());
				if(BarSpan.QUARTERLY.equals(chartModel.getBarSpan())){
					currentUnit /= 3;
				}
				
				if(currentUnit != previousUnit){
					iBar = createNewInstance(data.get(0));
					iBar.setOpen(bar.getOpen());
					iBar.setLow(Double.MAX_VALUE);
					iBar.setScrip(bar.getScrip());
					
				}
				copy(iBar, bar);
				
				if(currentUnit != previousUnit){
					modifiedData.add(iBar);
				}
				previousUnit = currentUnit;
			}
			chartModel.setData(modifiedData);
		}
	}

	private void copy(IBar one, IBar two){
		one.setClose(two.getClose());
		if(one.getHigh() < two.getHigh()){
			one.setHigh(two.getHigh());
		}
		if(one.getLow() > two.getLow()){
			one.setLow(two.getLow());
		}
		one.setDate(two.getDate());
		one.setVolume(one.getVolume()+two.getVolume());
	}
	
	private IBar createNewInstance(IBar bar){
		try {
			return bar.getClass().newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
